//
//  DataTables.swift
//  swiftDatatable
//
//  Created by 李朋 on 17/3/14.
//  Copyright © 2017年 李朋. All rights reserved.
//

import UIKit

private let dataCell = "dataCell"
private let heardID = "heardID"
private let footID = "footID"
class DataTables: UICollectionView {
    
    let rowViewmodel = rowViewModel.sharedModel
    
    var rowHeardStorTypes = [DataTableSortType]()
    
    lazy var columnHeaders = ["Id", "Name", "Email", "Number", "City", "Balance" ]
    
    fileprivate let highlightedColours = [
        UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1),
        UIColor(red: 0.9725, green: 0.9725, blue: 0.9725, alpha: 1)
    ]
    fileprivate let colours = [
        UIColor(red: 0.9725, green: 0.9725, blue: 0.9725, alpha: 1),
        UIColor.white
    ]
    
    init() {
        let layout = DatatableFlowLayout()
        super.init(frame: UIScreen.main.bounds, collectionViewLayout: layout)
        backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1)
        dataSource = self
        delegate = self
        scrollIndicatorInsets = UIEdgeInsetsMake(60, 0, 60, 0)
        rowViewmodel.dataArray = exampleDataSet()
        
        let array = rowViewmodel.dataArray[0]
        
        Array(0..<array.count).forEach { _ in
            rowHeardStorTypes.append(.unspecified)
        }
        
        register(UINib.init(nibName:String(describing: DataCollectionViewCell.self), bundle: nil), forCellWithReuseIdentifier: dataCell)
//        _ = rowViewmodel.getItemWith(i: 0)
        
        
        register(UINib(nibName: String(describing:CollectionHeardView.self), bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: heardID)
//        register(CollectionHeardView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: heardID)
        
        
        register(UINib(nibName: String(describing:CollectionHeardView.self), bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footID)
//        register(CollectionHeardView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footID)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension DataTables: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return rowViewmodel.dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return rowViewmodel.dataArray[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: dataCell, for: indexPath) as! DataCollectionViewCell
//        cell.backgroundColor = self.colours[safe:indexPath.section % 2]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let cell = cell as? DataCollectionViewCell {
            cell.textLabel.text = "\(rowViewmodel.dataArray[indexPath.section][indexPath.item])"
            cell.backgroundColor =  self.colours[indexPath.section % 2]
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader {
            let heardView = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: heardID, for: indexPath) as! CollectionHeardView
            heardView.titleLabel.text = columnHeaders[indexPath.item]
            heardView.didTapEvent = { [weak self] in
                //排序
                self?.sortData(index:indexPath.row)
            }
            heardView.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
            return heardView
        }else if kind == UICollectionElementKindSectionFooter {
        
            let footView = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: footID, for: indexPath) as! CollectionHeardView
            footView.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
            footView.titleLabel.text = columnHeaders[indexPath.item]
            return footView
        }
        return UICollectionReusableView()
    }
    
    
    
    
    func sortData(index:Int) {
        
        Array(0..<rowHeardStorTypes.count).forEach {
            if index == $0 {
                if DataTableSortType.ascending == rowHeardStorTypes[$0] ||
                    DataTableSortType.unspecified == rowHeardStorTypes[$0] {
                    rowHeardStorTypes[$0] = .descending
                }else {
                    rowHeardStorTypes[$0] = .ascending
                }
            }else {
                rowHeardStorTypes[$0] = .unspecified
            }
        }
        
        switch rowHeardStorTypes[index] {
        case .ascending:
            if 0 == index {
                rowViewmodel.dataArray.sort { ($0[index] as! Int) < ($1[index] as! Int) }
            }else {
                rowViewmodel.dataArray.sort { ($0[index] as! String) < ($1[index] as! String) }
            }
        case .unspecified,.descending:
            if 0 == index {
                rowViewmodel.dataArray.sort { ($0[index] as! Int) > ($1[index] as! Int) }
            }else {
                rowViewmodel.dataArray.sort { ($0[index] as! String) > ($1[index] as! String) }
            }
        }
        reloadData()
    }
//    
//    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//    {
//    CGSize size= {self.view.bounds.size.width, 100};
//    return size;
//    }
//    
    
    
//    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        DLog("选择了 + \(indexPath.section) + \(indexPath.row)")
//        
//        guard let cell = collectionView.cellForItem(at: indexPath) else {
//            return
//        }
//        
//        cell.backgroundColor = #colorLiteral(red: 0.2745098039, green: 0.5725490196, blue: 0.8980392157, alpha: 1)
//    }
//    
//    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
//        DLog("选择了 + \(indexPath.section) + \(indexPath.row)")
//        
//        guard let cell = collectionView.cellForItem(at: indexPath) else {
//            return
//        }
//        
//        cell.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
//    }

    

//    public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        guard let cellViewModel = self.rowViewModels[safe: indexPath.section]?[safe: indexPath.row] else {
//            return
//        }
//        if cellViewModel.highlighted {
//            cell.backgroundColor = self.highlightedColours[indexPath.section % 2]
//        }
//        else {
//            cell.backgroundColor = self.colours[indexPath.section % 2]
//        }
//    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if disableScrollViewLeftBounce {
            if (contentOffset.x <= 0) {
                contentOffset.x = 0
            }
        }
        
        if disableScrollViewTopBounce {
            if (contentOffset.y <= 0) {
                contentOffset.y = 0
            }
        }
        
        if disableScrollViewRightBounce {
            let maxX = contentSize.width-frame.width
            if (contentOffset.x >= maxX){
                contentOffset.x = max(maxX-1, 0)
            }
        }
        
        if disableScrollViewBottomBounce {
            let maxY = contentSize.height-frame.height
            if (contentOffset.y >= maxY){
                contentOffset.y = maxY-1
            }
        }
//
//        
//        if self.disableScrollViewLeftBounce() {
//            if (contentOffset.x <= 0) {
//                contentOffset.x = 0
//            }
//        }
//        
//        if self.disableScrollViewTopBounce() {
//            if (contentOffset.y <= 0) {
//                contentOffset.y = 0
//            }
//        }
//        
//        if self.disableScrollViewRightBounce(){
//            let maxX = contentSize.width-frame.width
//            if (contentOffset.x >= maxX){
//                contentOffset.x = max(maxX-1, 0)
//            }
//        }
//        
//        if self.disableScrollViewBottomBounce(){
//            let maxY = contentSize.height-frame.height
//            if (contentOffset.y >= maxY){
//                contentOffset.y = maxY-1
//            }
//        }
        
    }
    
    // MARK: - 添加动画
//    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        cell.contentView.alpha = 0
//        cell.transform = CGAffineTransform(scaleX: 0, y: 0).rotated(by: 0)
//        cell.contentView.alpha = 0;
//        UIView.animateKeyframes(withDuration: 0.5, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: 0), animations: {
//            
//            UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.8, animations: {
//                cell.contentView.alpha = 0.5;
//                cell.transform = CGAffineTransform(scaleX: 1.2, y: 1.2).rotated(by: 0)
//            })
//            
//            UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 0.2, animations: {
//                cell.contentView.alpha = 1;
//                cell.transform = CGAffineTransform(scaleX: 1, y: 1).rotated(by: 0)
//            })
//        }) { (finished) in
//
//        }
//    }
}

extension DataTables {
    fileprivate var disableScrollViewLeftBounce: Bool {
        return true
    }
    
    fileprivate var disableScrollViewTopBounce: Bool {
        return false
    }
    
    fileprivate var disableScrollViewRightBounce: Bool {
        return true
    }
    
    fileprivate var disableScrollViewBottomBounce: Bool {
        return false
    }
    
    
//    func disableScrollViewLeftBounce() -> Bool {
//        return true
//    }
//    func disableScrollViewTopBounce() -> Bool {
//        return false
//    }
//    func disableScrollViewRightBounce() -> Bool {
//        return true
//    }
//    func disableScrollViewBottomBounce() -> Bool {
//        return false
//    }
    
}


